<template>
    <view class="container">
        <view class="search-box">
            <input class="search-input" type="text" placeholder="请输入商品名称" placeholder-class="placeholder-style" 
                v-model="searchKeyword" @confirm="handleSearch">
        </view>
        <view v-if="currentStore">
            <view class="store-card">
                <image class="store-logo" :src="`/static/${currentStore.imgUrl}`" mode="aspectFill"></image>
                <view class="store-info">
                    <view class="store-name">{{currentStore.name}}</view>
                    <view class="store-stats">
                        <text>月售 {{currentStore.sales}}</text>
                        <text>起送 ¥{{currentStore.expressLimit}}</text>
                        <text>运费 ¥{{currentStore.expressPrice}}</text>
                    </view>
                    <view class="store-slogan">{{currentStore.slogan}}</view>
                </view>
                <view class="follow-btn" @click="toggleFollow" :class="{'followed': isFollowed}">
                    <text>{{isFollowed ? '取消关注' : '关注'}}</text>
                </view>
            </view>
            <view class="divider"></view>
        </view>
        <view class="content-wrapper">
            <view class="category-menu">
                <view @click="all()" :class="['menu-item', activeCategory === 'all' ? 'active' : '']">全部商品</view>
                <view @click="seckill()" :class="['menu-item', activeCategory ==='seckill' ? 'active' : '']">秒杀</view>
                <view @click="fruits()" :class="['menu-item', activeCategory === 'fruits' ? 'active' : '']">新鲜水果</view>
            </view>
            <scroll-view class="product-list" scroll-y>
                <view class="product-item" v-for="item in goods" :key="item._id">
                    <image :src="`/static/${item.imgUrl}`" class="product-image" mode="aspectFill"></image>
                    <view class="product-info">
                        <view class="product-name">{{item.name}}</view>
                        <view class="product-sales">月售 {{item.sales}} 件</view>
                        <view class="price-container">
                            <text class="current-price">¥{{item.price}}</text>
                            <text class="original-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
                            <view class="product-actions">
                                <text class="action-btn minus" @click.stop="decreaseQuantity(item)">-</text>
                                <text class="product-quantity">{{getCartQuantity(item._id)}}</text>
                                <text class="action-btn plus" @click.stop="increaseQuantity(item)">+</text>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
        <view class="cart-footer">
            <view class="cart-icon" @click="toggleCartPopup">
                <image src="/static/imgs/assets/basket.png" />
                <view class="badge" v-if="cartCount > 0">{{cartCount}}</view>
            </view>
            <view class="price-info">
                <text>总计:</text>
                <text class="total-price">¥{{currentStoreTotalPrice.toFixed(2)}}</text>
            </view>
            <view class="checkout-btn" @click="goToCart">去结算</view>
        </view>
        <view class="cart-popup" v-if="showCartPopup" @click="toggleCartPopup">
            <view class="popup-content" @click.stop>
                <view class="popup-header">
                    <text class="clear-cart" @click="clearCurrentStoreCart">清空购物车</text>
                </view>
                <scroll-view class="cart-list" scroll-y>
                    <view class="store-group" v-if="currentStoreCartItems.length > 0">
                        <view class="store-title">
                            <checkbox :checked="isCurrentStoreAllSelected" @click="toggleCurrentStoreSelection">
                                {{currentStore.name}}
                            </checkbox>
                        </view>
                        <view class="cart-item" v-for="item in currentStoreCartItems" :key="item._id">
                            <image :src="`/static/${item.imgUrl}`" class="cart-item-image"></image>
                            <view class="cart-item-info">
                                <view class="cart-item-name">{{item.name}}</view>
                                <view class="cart-item-sales">月售 {{item.sales}} 件</view>
                                <view class="price-container">
                                    <view class="price-info">
                                        <text class="current-price">¥{{item.price}}</text>
                                        <text class="original-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
                                        <text class="subtotal">小计: ¥{{(item.price * item.quantity).toFixed(2)}}</text>
                                    </view>
                                    <view class="product-actions">
                                        <text class="action-btn minus" @click.stop="decreaseQuantity(item)">-</text>
                                        <text class="product-quantity">{{item.quantity}}</text>
                                        <text class="action-btn plus" @click.stop="increaseQuantity(item)">+</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view v-else class="empty-cart">
                        <image src="/static/imgs/assets/empty-cart.png" mode="aspectFit"></image>
                        <text>购物车是空的</text>
                    </view>
                </scroll-view>
                <view class="cart-total">
                    <view class="cart-icon">
                        <image src="/static/imgs/assets/basket.png" />
                        <view class="badge" v-if="currentStoreCartCount > 0">{{currentStoreCartCount}}</view>
                    </view>
                    <view class="total-price-container">
                        <text>已选 {{currentStoreSelectedCount}} 件</text>
                        <text>合计:</text>
                        <text class="total-price">¥{{currentStoreTotalPrice.toFixed(2)}}</text>
                    </view>
                    <view class="checkout-btn" @click="goToCart">去结算</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import Config from '@/Config.js'

export default {
    data() {
        return {
            currentStore: {},
            goods: [],
            superId: null,
            activeCategory: 'all',
            cartItems: [],
            showCartPopup: false,
            phoneNumber: '',
            searchKeyword: '',
            originalGoods: [],
            isFollowed: false,
            userInfo: {}
        };
    },
    computed: {
        currentStoreCartItems() {
            return this.cartItems.filter(item => item.storeId === this.superId && item.phoneNumber === this.phoneNumber);
        },
        currentStoreCartCount() {
            return this.currentStoreCartItems.reduce((total, item) => total + item.quantity, 0);
        },
        cartCount() {
            return this.cartItems.filter(item => item.phoneNumber === this.phoneNumber).reduce((total, item) => total + item.quantity, 0);
        },
        currentStoreSelectedCount() {
            return this.currentStoreCartItems.reduce((count, item) => {
                return count + (item.isSelected? item.quantity : 0);
            }, 0);
        },
        isCurrentStoreAllSelected() {
            return this.currentStoreCartItems.length > 0 &&
                this.currentStoreCartItems.every(item => item.isSelected);
        },
        currentStoreTotalPrice() {
            return this.currentStoreCartItems.reduce((total, item) => {
                return total + (item.isSelected? item.price * item.quantity : 0);
            }, 0);
        }
    },
    onLoad(options) {
        this.superId = options.id;
        this.phoneNumber = uni.getStorageSync('currentPhone');
        this.loadStoreData();
        this.loadCartData();
        this.loadUserInfo();
        this.all();
    },
    methods: {
        loadStoreData() {
            uni.request({
                url: Config.URL + `hotList?_id=${this.superId}`,
                success: (res) => {
                    this.currentStore = res.data[0];
                }
            });
        },
        loadCartData() {
            const savedCartItems = uni.getStorageSync('cartItems') || [];
            this.cartItems = savedCartItems.filter(item => item.phoneNumber === this.phoneNumber);
        },
        loadUserInfo() {
            if (!this.phoneNumber) {
                console.log('No phone number found');
                return;
            }
            
            uni.request({
                url: Config.URL + `users?phone=${this.phoneNumber}`,
                success: (res) => {
                    console.log('Load user info response:', res);
                    if (res.statusCode === 200 && res.data && res.data.length > 0) {
                        this.userInfo = res.data[0];
                        // 确保follows字段存在
                        if (!this.userInfo.follows) {
                            this.userInfo.follows = [];
                        }
                        this.isFollowed = this.userInfo.follows.includes(this.superId);
                    } else {
                        // 如果用户不存在，创建新用户
                        this.createNewUser();
                    }
                },
                fail: (err) => {
                    console.error('Error loading user info:', err);
                    uni.showToast({
                        title: '加载用户信息失败',
                        icon: 'none'
                    });
                }
            });
        },
        createNewUser() {
            const newUser = {
                phone: this.phoneNumber,
                follows: [],
                addresses: [],
                order: []
            };
            
            uni.request({
                url: Config.URL + 'users',
                method: 'POST',
                data: newUser,
                success: (res) => {
                    if (res.statusCode === 201 || res.statusCode === 200) {
                        this.userInfo = res.data;
                        this.loadUserInfo();
                    } else {
                        uni.showToast({
                            title: '创建用户信息失败',
                            icon: 'none'
                        });
                    }
                },
                fail: () => {
                    uni.showToast({
                        title: '创建用户信息失败',
                        icon: 'none'
                    });
                }
            });
        },
        all() {
            this.activeCategory = 'all';
            this.fetchProducts(Config.URL + `products-all?shopId=${this.superId}`);
        },
        seckill() {
            this.activeCategory ='seckill';
            this.fetchProducts(Config.URL + `products-seckill?shopId=${this.superId}`);
        },
        fruits() {
            this.activeCategory = 'fruits';
            this.fetchProducts(Config.URL + `products-fruit?shopId=${this.superId}`);
        },
        fetchProducts(url) {
            uni.request({
                url: url,
                success: (res) => {
                    this.goods = res.data;
                    this.originalGoods = res.data;
                }
            });
        },
        toggleCartPopup() {
            this.showCartPopup =!this.showCartPopup;
        },
        increaseQuantity(item) {
            const existingItem = this.cartItems.find(i => i._id === item._id && i.phoneNumber === this.phoneNumber);
            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                this.addNewItemToCart(item);
            }
            this.saveCartData();
        },
        decreaseQuantity(item) {
            const existingItem = this.cartItems.find(i => i._id === item._id && i.phoneNumber === this.phoneNumber);
            if (existingItem) {
                if (existingItem.quantity > 1) {
                    existingItem.quantity -= 1;
                } else {
                    this.cartItems = this.cartItems.filter(i => i._id!== item._id || i.phoneNumber!== this.phoneNumber);
                }
                this.saveCartData();
            }
        },
        addNewItemToCart(item) {
            this.cartItems.push({
               ...item,
                quantity: 1,
                isSelected: true,
                storeId: this.superId,
                storeName: this.currentStore.name,
                phoneNumber: this.phoneNumber
            });
        },
        getCartQuantity(productId) {
            const item = this.cartItems.find(i => i._id === productId && i.phoneNumber === this.phoneNumber);
            return item? item.quantity : 0;
        },
        clearCurrentStoreCart() {
            this.cartItems = this.cartItems.filter(item => item.storeId!== this.superId || item.phoneNumber!== this.phoneNumber);
            this.saveCartData();
            this.showCartPopup = false;
        },
        toggleCurrentStoreSelection() {
            const newState =!this.isCurrentStoreAllSelected;
            this.currentStoreCartItems.forEach(item => {
                item.isSelected = newState;
            });
            this.saveCartData();
        },
        saveCartData() {
            uni.setStorageSync('cartItems', this.cartItems);
        },
        goToCart() {
            const selectedItems = this.currentStoreCartItems.filter(item => item.isSelected);
            if (selectedItems.length === 0) {
                uni.showToast({
                    title: '请选择要结算的商品',
                    icon: 'none'
                });
                return;
            }
            uni.setStorageSync('selectedCartItems', selectedItems);
            uni.navigateTo({
                url: '/pages/must/must'
            });
        },
        handleSearch() {
            if (!this.searchKeyword.trim()) {
                this.goods = this.originalGoods;
                return;
            }
            this.goods = this.originalGoods.filter(item => 
                item.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
            );
        },
        toggleFollow() {
            if (!this.phoneNumber) {
                uni.showToast({
                    title: '请先登录',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.userInfo || !this.userInfo.id) {
                this.loadUserInfo();
                uni.showToast({
                    title: '正在加载用户信息，请稍后重试',
                    icon: 'none'
                });
                return;
            }
            
            // 准备新的关注列表
            let newFollows = [...(this.userInfo.follows || [])];
            if (this.isFollowed) {
                // 取消关注
                newFollows = newFollows.filter(id => id !== this.superId);
            } else {
                // 添加关注
                if (!newFollows.includes(this.superId)) {
                    newFollows.push(this.superId);
                }
            }
            
            // 更新用户数据
            const updateData = {
                ...this.userInfo,
                follows: newFollows
            };
            
            console.log('Updating user with data:', updateData);
            
            uni.request({
                url: Config.URL + `users/${this.userInfo.id}`,
                method: 'PUT',
                data: updateData,
                success: (res) => {
                    console.log('Update response:', res);
                    if (res.statusCode === 200 || res.statusCode === 201) {
                        this.userInfo.follows = newFollows;
                        this.isFollowed = !this.isFollowed;
                        
                        uni.showToast({
                            title: this.isFollowed ? '关注成功' : '取消关注成功',
                            icon: 'success'
                        });
                        
                        // 触发页面刷新
                        this.loadUserInfo();
                    } else {
                        console.error('Update failed:', res);
                        uni.showToast({
                            title: '操作失败，请重试',
                            icon: 'none'
                        });
                    }
                },
                fail: (err) => {
                    console.error('Network error:', err);
                    uni.showToast({
                        title: '网络错误，请重试',
                        icon: 'none'
                    });
                }
            });
        }
    }
};
</script>

<style scoped>
.price-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20rpx;
}
.product-actions {
    display: flex;
    align-items: center;
    gap: 15rpx;
}
.action-btn {
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
}
.plus {
    background-color: #1b76f6;
    color: #fff;
}
.minus {
    background-color: #f5f5f5;
    color: #666;
}
.product-quantity {
    min-width: 40rpx;
    text-align: center;
    font-size: 28rpx;
}
.container {
    padding-bottom: 100rpx;
    background-color: #f8f8f8;
    min-height: 100vh;
}
.search-box {
    padding: 20rpx 30rpx;
    background-color: #fff;
}
.search-input {
    height: 70rpx;
    background-color: #f5f5f5;
    border-radius: 35rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
}
.placeholder-style {
    color: #999;
}
.store-card {
    display: flex;
    padding: 30rpx;
    background-color: #fff;
    position: relative;
}
.store-logo {
    width: 140rpx;
    height: 140rpx;
    border-radius: 8rpx;
}
.store-info {
    flex: 1;
    margin-left: 30rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.store-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}
.store-stats {
    font-size: 24rpx;
    color: #666;
}
.store-stats text {
    margin-right: 20rpx;
}
.store-slogan {
    font-size: 24rpx;
    color: #e74c3c;
}
.divider {
    height: 20rpx;
    background-color: #f5f5f5;
}
.content-wrapper {
    display: flex;
    height: calc(100vh - 400rpx);
}
.category-menu {
    width: 180rpx;
    background-color: #fff;
}
.menu-item {
    padding: 30rpx 20rpx;
    font-size: 28rpx;
    color: #666;
    text-align: center;
    border-left: 6rpx solid transparent;
}
.menu-item.active {
    color: #e74c3c;
    font-weight: bold;
    border-left-color: #e74c3c;
    background-color: #fef0f0;
}
.product-list {
    flex: 1;
    padding: 20rpx;
    background-color: #fff;
}
.product-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
}
.product-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
}
.product-info {
    flex: 1;
    margin-left: 20rpx;
    position: relative;
}
.product-name {
    font-size: 28rpx;
    color: #333;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}
.product-sales {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
}
.price-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20rpx;
}
.current-price {
    font-size: 32rpx;
    color: #e74c3c;
    font-weight: bold;
}
.original-price {
    font-size: 24rpx;
    color: #999;
    text-decoration: line-through;
    margin-left: 10rpx;
}
.cart-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
    z-index: 10;
}
.cart-icon {
    position: relative;
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
}
.cart-icon image {
    width: 70px;
    height: 35px;
    margin-left: 25px;
}
.cart-icon.iconfont {
    color: #fff;
    font-size: 40rpx;
}
.badge {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    min-width: 36rpx;
    height: 36rpx;
    background-color: #e74c3c;
    color: #fff;
    border-radius: 18rpx;
    font-size: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8rpx;
}
.price-info {
    flex: 1;
    font-size: 28rpx;
    color: #666;
}
.total-price {
    color: #e74c3c;
    font-weight: bold;
    margin-left: 15px;
}
.checkout-btn {
    width: 200rpx;
    height: 70rpx;
    background-color: #1b76f6;
    color: #fff;
    font-size: 28rpx;
    border-radius: 35rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}
.cart-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 100;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
}
.popup-content {
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    max-height: 70vh;
    padding: 30rpx;
}
.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #eee;
}
.select-all {
    display: flex;
    align-items: center;
}
.select-all checkbox {
    margin-right: 10rpx;
}
.clear-cart {
    font-size: 26rpx;
    color: #666;
}
.cart-list {
    max-height: 50vh;
    margin-top: 20rpx;
}
.cart-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
}
.select-item {
    margin-right: 10rpx;
}
.cart-item-image {
    width: 100rpx;
    height: 100rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
}
.cart-item-info {
    flex: 1;
}
.cart-item-name {
    font-size: 28rpx;
    margin-bottom: 5rpx;
}
.cart-item-sales {
    font-size: 24rpx;
    color: #999;
}
.price-container {
    display: flex;
    align-items: center;
}
.current-price {
    font-size: 32rpx;
    color: #e74c3c;
    font-weight: bold;
}
.original-price {
    font-size: 24rpx;
    color: #999;
    text-decoration: line-through;
    margin-left: 10rpx;
}
.cart-total {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20rpx;
}
.cart-icon {
    position: relative;
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
}
.cart-icon image {
    width: 70px;
    height: 35px;
    margin-left: 25px;
}
.badge {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    min-width: 36rpx;
    height: 36rpx;
    background-color: #e74c3c;
    color: #fff;
    border-radius: 18rpx;
    font-size: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8rpx;
}
.total-price-container {
    display: flex;
    align-items: center;
}
.total-price {
    color: #e74c3c;
    font-weight: bold;
    margin-left: 10rpx;
}
.checkout-btn {
    width: 200rpx;
    height: 70rpx;
    background-color: #1b76f6;
    color: #fff;
    font-size: 28rpx;
    border-radius: 35rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}
.store-group {
    margin-bottom: 20rpx;
    background: #fff;
    border-radius: 12rpx;
}
.store-title {
    padding: 20rpx;
    font-size: 28rpx;
    font-weight: bold;
    border-bottom: 1rpx solid #f5f5f5;
}
.subtotal {
    font-size: 24rpx;
    color: #666;
    margin-left: 20rpx;
}
.price-info {
    display: flex;
    align-items: center;
    flex: 1;
}
.total-price-container text {
    margin-right: 10rpx;
}
.empty-cart {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
}
.empty-cart image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
}
.empty-cart text {
    color: #999;
    font-size: 28rpx;
}
.follow-btn {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
    padding: 6px 15px;
    background-color: #007aff;
    color: white;
    border-radius: 15px;
    display: inline-block;
    font-size: 12px;
    box-shadow: 0 2px 5px rgba(0, 122, 255, 0.3);
    transition: all 0.3s ease;
}

.follow-btn.followed {
    background-color: #f5f5f5;
    color: #666;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.follow-btn:active {
    transform: scale(0.95);
}
</style>    